package com.example.bledemo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

public class BleDeviceWRActivity extends Activity {

    int position;
    String mac;

    private boolean isConnectState;
    BluetoothDevice device;

    Button bleConnectButton = null; //(Button)findViewById(R.id.connectBleDevice);
    TextView readDataTextView = null;//(TextView)findViewById(R.id.readDataTextView);


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ble_operate);

        bleConnectButton = (Button)findViewById(R.id.connectBleDevice);
        readDataTextView = (TextView)findViewById(R.id.readDataTextView);

        //接收传来的值并显示
        Intent intent = getIntent();
        position = intent.getIntExtra("position",-1);

        // TODO Auto-generated method stub
        Toast.makeText(BleDeviceWRActivity.this, String.valueOf(MainActivity.mBleAdapter.getItem(position)), Toast.LENGTH_LONG).show();
        Log.d("********", String.valueOf(position));

        mac = String.valueOf(MainActivity.mBleAdapter.getItem(position));
        MainActivity.mBluetoothAdapter.cancelDiscovery();
        device = MainActivity.mDeviceList.get(position);
        MainActivity.mBluetoothGatt = device.connectGatt(BleDeviceWRActivity.this, false, mGattCallback);

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void onConnectDevice(View view) {
        if(!isConnectState) {
            MainActivity.mBluetoothGatt = device.connectGatt(BleDeviceWRActivity.this, false, mGattCallback);
            bleConnectButton.setText("连接中");
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void readDeviceData(View view) {
        if(!isConnectState)
        {
            Toast.makeText(this, "请先连接蓝牙设备", Toast.LENGTH_LONG).show();

        }
        else
        {
            BluetoothGattService service = MainActivity.mBluetoothGatt.getService(UUID.fromString("00001800-0000-1000-8000-00805f9b34fb"));
            BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("00002a00-0000-1000-8000-00805f9b34fb"));
            MainActivity.mBluetoothGatt.readCharacteristic(characteristic);
        }
    }

    // Implements callback methods for GATT events that the app cares about.  For example,
    // connection change and services discovered.
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            Log.e("gatt=", gatt.toString() );

            if(newState == BluetoothProfile.STATE_CONNECTED){
                gatt.discoverServices();

            }else if(newState == BluetoothProfile.STATE_DISCONNECTED) {
                if (gatt != null) {
                    gatt.close();
                }

                isConnectState = false;

                bleConnectButton.post(new Runnable() {
                    @Override
                    public void run() {
                        bleConnectButton.setText("连接");
                    }
                });

            }
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            List<BluetoothGattService> serviceList = gatt.getServices();
            for(BluetoothGattService service : serviceList){
                Log.d("service uuid",service.getUuid().toString());
                List<BluetoothGattCharacteristic> characteristicList = service.getCharacteristics();
                for (BluetoothGattCharacteristic characteristic : characteristicList){
                    Log.d("charac uuid",characteristic.getUuid().toString());
                    List<BluetoothGattDescriptor> descriptorList = characteristic.getDescriptors();
                    for (BluetoothGattDescriptor descriptor : descriptorList){
                        Log.d("descriptor uuid",descriptor.getUuid().toString());
                    }
                }
                isConnectState = true;
                bleConnectButton.post(new Runnable() {
                    @Override
                    public void run() {
                        bleConnectButton.setText("已连接");
                    }
                });

            }
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            Log.d("onCharacteristicRead","读取的回调"+ Arrays.toString(characteristic.getValue()));
            String s = "null";
            try {
                s=new String(characteristic.getValue(),"ascii");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String finalS = s;
            readDataTextView.post(new Runnable() {
                @Override
                public void run() {
                    readDataTextView.setText(finalS);
                }
            });

        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);

        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
        }

        @Override
        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorRead(gatt, descriptor, status);
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorWrite(gatt, descriptor, status);
        }
    };


}
